const formatPrice = function (price) {
  // console.log(price)
  price += ''

  if (price.length == 0 || price == '') {
    return {
      big: '0',
      small: '00'
    }
  }

  const pl = price.split('.')

  if (pl.length === 1) {
    return {
      big: pl[0],
      small: '00'
    }
  }

  if (pl[1] < 10 && pl[1].length === 1) {
    pl[1] = pl[1] + '0'
  }

  return {
    big: pl[0],
    small: pl[1]
  }
}

// 精确位，多少个0代表精确后面多少位
const num = 100000

/**
 * 计算 price * count解决精度损失
 * @param {价格} price
 * @param {数量} count
 * @returns
 */
function calculateTotalPrice(price, count) {
  const priceInCents = Math.round(price * num)
  const quantity = count

  // 将结果转换回元（除以 100）
  return (priceInCents * quantity) / num
}

/**
 * 计算 price + price2
 * @param {*} price
 * @param {*} price2
 */
function calculateAddPrice(price, price2) {
  if (price.length === 0) {
    price = 0
  }

  if (price2.length === 0) {
    price2 = 0
  }

  if (typeof price == 'string') {
    price = parseFloat(price)
  }

  if (typeof price2 == 'string') {
    price2 = parseFloat(price2)
  }

  const priceInCents = Math.round(price * num)
  const priceInCents2 = Math.round(price2 * num)

  return (priceInCents + priceInCents2) / num
}

/**
 * 计算 price - price2
 * @param {*} price
 * @param {*} price2
 * @returns
 */
function calculateSubPrice(price, price2) {
  const priceInCents = Math.round(price * num)
  const priceInCents2 = Math.round(price2 * num)

  return (priceInCents - priceInCents2) / num
}

/**
 * 计算 price / count解决精度损失
 * @param {价格} price
 * @param {数量} count
 * @returns
 */
function calculateAveragePrice(price, count) {
  if (count == 0) {
    console.log('价格被除数为0')
    return 0
  }

  const priceInCents = Math.round(price * num)
  const quantity = count

  // 将结果转换回元（除以 100）
  return priceInCents / quantity / num
}

// 返回打折的金额 price * discountt
function calculateDiscountPrice(price, discount) {
  const priceInCents = Math.round(price * num)
  const discountt = discount * 10
  // console.log(priceInCents, discountt)
  // console.log((priceInCents * discountt) / 1000)

  // 将结果转换回元（除以 100）
  return (priceInCents * discountt) / num / 10
}

export {
  formatPrice,
  calculateTotalPrice,
  calculateAddPrice,
  calculateSubPrice,
  calculateAveragePrice,
  calculateDiscountPrice
}
